package newtank.view;


import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 坦克大战展示层画布
 * @author lijiahao
 * @since 2022/1/27
 */
public class TankDrawingCloth extends JPanel {

    private static final long serialVersionUID = 3436471162649734451L;
    private List<PaintView> paintViews;
    private Map<String, PaintView> paintViewMap;
    private Graphics graphics = null;
    private Graphics2D g2d = null;

    public TankDrawingCloth(Color clothColor) {
        super();
        setBackground(clothColor);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(paintViews == null || paintViews.size() == 0) {
            throw new RuntimeException("没有初始化坦克");
        }
        if(this.graphics == null) {
            this.graphics = g;
        }
        doDrawing(paintViews);
    }

    public void doDrawing(List<PaintView> paintViewList) {
        if(paintViewList == null || paintViewList.size() == 0) {
            return ;
        }
        if(g2d == null) {
            g2d = (Graphics2D) this.graphics.create();
        }
        paintViewList.forEach(view -> view.draw(g2d));
    }

    public void resetPaintView(List<PaintView> paintViews) {
        this.paintViews = paintViews;
        this.paintViewMap = paintViews
                .stream()
                .collect(Collectors.toMap(PaintView::getIdentity, Function.identity()));

    }

    public void addPaintView(List<PaintView> paintViews) {
        this.paintViews.addAll(paintViews);
        this.paintViewMap = this.paintViews
                .stream()
                .collect(Collectors.toMap(PaintView::getIdentity, Function.identity()));
    }

    public void addPaintView(PaintView paintView) {
        if(this.paintViewMap.getOrDefault(paintView.getIdentity(), null) == null) {
            this.paintViews.add(paintView);
            this.paintViewMap.put(paintView.getIdentity(), paintView);
        }
    }

    public void drawView(String identity) {
        if(this.paintViewMap == null) {
            return;
        }
        PaintView view = paintViewMap.get(identity);
        view.draw(this.g2d);
    }

    public void clearDraw(String identity) {
        if(this.paintViewMap == null) {
            return;
        }
        PaintView view = paintViewMap.get(identity);
    }

    public PaintView getView(String viewName) {
        return paintViewMap.get(viewName);
    }
}
